package com.study.ju.web.interceptor;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * <p>https://blog.csdn.net/kaizhangzhang/article/details/97900961</p>
 *
 * @author chentao
 * @version v 0.1 2023/5/29 15:37
 */
public class ResettableServletRequestWrapper extends HttpServletRequestWrapper {
    //保存流中的数据
    private byte[] data;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request
     * @throws IllegalArgumentException if the request is null
     */
    public ResettableServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //从流中获取数据
        data = IOUtils.toByteArray(request.getInputStream());
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        //在调用getInputStream函数时，创建新的流，包含原先数据流中的信息，然后返回
        return new NewServletInputStream(new ByteArrayInputStream(data));
    }

    class NewServletInputStream extends ServletInputStream{
        private InputStream inputStream;

        public NewServletInputStream(InputStream inputStream){
            this.inputStream = inputStream;
        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }


}
